package com.suxiaoxiao.springbootlearn.designpattern.observerpattern.subject;

import com.suxiaoxiao.springbootlearn.designpattern.observerpattern.observer.Observer;

import java.util.ArrayList;

/**
 * 具体的主题
 * 天气数据主题
 * @author 、
 */
public class WeatherData implements Subject {

    /**
     * 观察者们
     * 跟我想的一样，吧观察者放到数组中。
     */
    private ArrayList<Observer> observers;

    /**
     * 温度
     */
    private float temperature;
    /**
     * 湿度
     */
    private float humidity;
    /**
     * 气压
     */
    private float pressure;

    /**
     * 初始化行为放到构造函数中
     */
    public WeatherData() {
        this.observers = new ArrayList<>();
    }

    @Override
    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        int i = observers.indexOf(observer);
        if (i >= 0) {
            observers.remove(i);
        }
    }

    @Override
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(temperature, humidity, pressure);
        }
    }

    public void measurementsChanged() {
        notifyObservers();
    }

    public void setMeasurements(float temperature, float humidity, float pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }

}
